package api

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm/clause"
	"zhonghui/console/service"
	"zhonghui/console/structs"
	"zhonghui/console/warehouse/dbx/db_zh_kernel"
	"zhonghui/console/warehouse/logx"
	"zhonghui/console/warehouse/modelx/model_zh_kernel"
	"zhonghui/console/warehouse/respx"
)

func (server *Server) ImportPolicy(c *gin.Context) {
	req := structs.ImportPolicyReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		respx.Bad(c, err)
		return
	}

	data, err := service.ParseImportPolicy(c, req.Source)
	if err != nil {
		logx.ZapTrace(c).Errorw("导入失败", "err", err)
		respx.Alert(c, "导入失败请检查表格式")
		return
	}

	if len(data) == 0 {
		respx.Alert(c, "解析数据结果为0，请检查表格式")
		return
	}

	batch := make([]model_zh_kernel.Policy, 0)
	for _, d := range data {
		p := model_zh_kernel.Policy{
			No:       d.No,
			Holder:   d.Holder,
			Phone:    d.Phone,
			InsureAt: d.InsureAt,
		}
		batch = append(batch, p)
	}
	db_zh_kernel.Client().Clauses(clause.Insert{Modifier: "IGNORE"}).CreateInBatches(batch, 1000)

	respx.Success(c, gin.H{"ct": len(data)}, nil)
}
